package cn.hjh.dao;

import cn.hjh.pojo.Spare;
import cn.hjh.pojo.Users;
import org.hibernate.Query;


import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

public class SpareDao {

    public void save(Spare spare){
        HibernateUtil.currentSession().save(spare);
    }

    public Spare get(Serializable id){
        return (Spare) HibernateUtil.currentSession().get(Users.class,id);
    }

    public void delete(Spare spare){
        HibernateUtil.currentSession().delete(spare);
    }

    /* 第5章简答题 */
    public List<Spare> findSpareBysparemodel(String sparemodel){
        String hql = "from Spare  where sparemodel = ?";
        Query query = HibernateUtil.currentSession().createQuery(hql);
        query.setString(0,sparemodel);
        return query.list();
    }

    //查询出厂价格小于指定价格的备件
    public List<Spare> findSpareByprice(){
        String hql = "from Spare where price < ?";
        Query query = HibernateUtil.currentSession().createQuery(hql);
        query.setInteger(0,640);
        List<Spare> spares = query.list();
        return spares;
    }

    //查询出厂日期小于指定日期的备件
    public List<Spare> findSpareByriqi(){
        String hql = "from Spare where production = ?";
        Query query = HibernateUtil.currentSession().createQuery(hql);
        try {
            query.setDate(0,new SimpleDateFormat("yyyy-MM-dd").parse("2008-10-24"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<Spare> spares = query.list();
        return spares;
    }

    public List<Spare> finSpareBysan(Spare conditions){
        String hql = "from Spare where sparemodel = :sparemodel and price = :price and production = :production";
        Query query = HibernateUtil.currentSession().createQuery(hql);
        query.setProperties(conditions);
        //query.setString("sparemodel","%"+sparemodel+"%");
        return query.list();
    }
}
